package com.learnpilot.datechange.service.impl;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.learnpilot.datechange.service.CurrentInternetTime;

public class CurrentInternetTimeImpl implements CurrentInternetTime{
	final Logger LOG = LoggerFactory.getLogger(CurrentInternetTimeImpl.class);
	//private String TIME_SERVER_IST = "time-a.nist.gov";
	private String TIME_SERVER_NEW_YORK_CITY = "nist1-ny2.ustiming.org ";

	public Date getCurrentDateFromInternet() {
		NTPUDPClient timeClient = new NTPUDPClient();
		Date currentDate = new Date();

		try {
			InetAddress inetAddress = InetAddress.getByName(TIME_SERVER_NEW_YORK_CITY);
		    TimeInfo timeInfo = timeClient.getTime(inetAddress);
			long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();
			currentDate = new Date(returnTime);
			LOG.debug("System date from internet:  "+currentDate);
		} catch (UnknownHostException e) {
			LOG.error("Could not get current time "+e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			LOG.error("Could not get current time "+e.getMessage());
			e.printStackTrace();
		}
		return currentDate;
    }

	/*public Date getCurrentDateFromInternetNotWorking() {
	    DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
	    String currentTimeURL = "http://webservice.theknot.com/Time/GetTime.asmx/currentTime";
		XmlUtil xmlUtil = new XmlUtil();
		Date currentDate = null;
		try {

			URL url = new URL(currentTimeURL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "application/xml");
			if (conn.getResponseCode() != 200) {
				LOG.error("Failed to get current time : "+ conn.getResponseCode());
				throw new Exception();
			}
			BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
			String output;
			StringBuilder xmlString = new StringBuilder();
			while ((output = br.readLine()) != null) {
				xmlString.append(output);
			}
			Document currentTimeDoc = xmlUtil.getXMLFromString(xmlString.toString());
			//currentTimeDoc.getDocumentElement().normalize();
			String[] dateNTime = currentTimeDoc.getDocumentElement().getTextContent().split(" ");
			try {
				currentDate = df.parse(dateNTime[0]);
			} catch (ParseException e) {
				e.printStackTrace();
				LOG.error("Could not parse the date : "+dateNTime[0] );
			}

			conn.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e){
			LOG.error("Failed to get time from internet. Set it to system time.");
			return new Date();
		}
		return currentDate;
	}*/


}